
import json
from flask import Blueprint,jsonify,g
from flask_restful import Api,Resource,marshal,reqparse

from models import db
from models.user import Channel,News,UserModel,Collection
from common.model_fields.user import channel_fields,news_fields
from common.uitils.login_utils import login_required

channel_bp = Blueprint('channel',__name__,url_prefix='/news')

api = Api(channel_bp)


class ChannelsResource(Resource):
    def get(self):
        """获取所有的频道信息"""
        channels = Channel.query.all()
        return jsonify(data=marshal(channels, channel_fields))


class NewsByChannel(Resource):
    def get(self):
        """根据频道的id 获取文章信息"""
        parser = reqparse.RequestParser()
        parser.add_argument('category')
        args = parser.parse_args()
        cate_id = args.get('category')
        print("获取到的文章》》", cate_id)
        news = News.query.filter_by(channel_id=cate_id).all()
        print("news>>>>>", news)
        # 把有序字典转成字典,然后给每篇文章添加作者信息
        datas = json.loads(json.dumps(marshal(news, news_fields)))
        print("datas>>>>", datas)
        for new in datas:
            user = UserModel.query.filter_by(uid=new['user_id']).first()
            new['nick_name'] = user.uname
        print('news_datas>>>>', datas)
        return jsonify(message='ok', code=200, data={'news': datas})


class NewInfo(Resource):
    def get(self,id):
        """根据频道id 获取文章详情"""
        new = News.query.filter_by(nid=id).first()
        # 把有序字典转成字典,然后给每篇文章添加作者信息
        data = json.loads(json.dumps(marshal(new, news_fields)))
        user = UserModel.query.filter_by(uid=new.user_id).first()
        data['nick_name'] = user.uname

        # 从评论中获取
        comment_data = [{'id':i.cmid, 'art_id':i.article_id,
                         'like_count':i.like_count,
                         "reply_count":i.reply_count,
                         'content':i.content,
                         'comment_length':len(new.comment)} for i in new.comment]
        data['comment'] = comment_data
        return jsonify(message='ok',code=200, data=data)

    # @login_required
    def post(self,id):
        """
        根据频道id添加该频道的文章
        """
        # uid = g.user_id
        parser = reqparse.RequestParser()
        parser.add_argument('content')
        parser.add_argument('title')
        parser.add_argument('uid')
        args = parser.parse_args()
        content = args.get('content')
        uid = args.get('uid')
        title = args.get('title')
        news = News(user_id=uid, channel_id=id, content=content, title=title)
        db.session.add(news)
        db.session.commit()
        return jsonify(message='ok', code=200)

    def delete(self,id):
        if not id:
            return jsonify(message='No,没有该文章', code=204)
        News.query.filter_by(nid=id).delete()
        db.session.commit()
        return jsonify(message='ok,删除成功', code=200)



class CollectionResource(Resource):

    @login_required
    def get(self,nid):
        """
        添加文章收藏
        1. 实现这个功能前提是必须先登录
        2. 只有登录后的才能实现点赞
        3. 从收藏表去查询,文章是否被收藏: 根据user_id, news_id 去查询,返回的是一个文章信息
        :param id:  文章的id
        :return:
        """
        # 获取当前登录的用户id
        uid = g.user_id
        rest = Collection.query.filter_by(user_id=uid, news_id=nid).first()
        # 若过滤出信息, 修改文章的is_collection的值
        if not rest:
            # 创建收藏表
            collect = Collection(user_id=uid, news_id=nid)
            db.session.add(collect)
            db.session.commit()
            # 修改的是收藏的状态
            News.query.filter_by(nid=nid).update({'is_collection': 1})
            db.session.commit()
            return jsonify(message='收藏成功', code=200)
        else:
            # 取消收藏时要把收藏表中的数据删除, 但是不会物理删除, 只是逻辑删除
            Collection.query.filter_by(user_id=uid, news_id=nid).update({'is_delete':False})
            db.session.commit()
            # 没有结果说明取消收藏
            News.query.filter_by(nid=nid).update({'is_collection': 0})
            db.session.commit()
            return jsonify(message='取消收藏成功', code=200)


api.add_resource(ChannelsResource,'/channels')
api.add_resource(NewsByChannel,'/channel')
api.add_resource(NewInfo, '/info/<int:id>')
api.add_resource(CollectionResource,'/starts/<int:nid>')


